from flask import Flask, render_template
from jinja2 import Environment, FileSystemLoader
from markupsafe import Markup
from pyecharts.charts.base import Base
from pyecharts.globals import CurrentConfig

import dbs
import visualizations
from utils import FlaskSignal

CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./templates"))
app = Flask(__name__, static_folder="templates")


class FlaskSig(FlaskSignal):

    def receive(self, sender, data: str, **extra):
        print(f'signal received, sender:{sender}, data:{data}, extra:{extra}')


signal = FlaskSig(id="sig")


@app.get("/")
@app.get("/index")
def index():
    signal.send("index", data="1", ack=True)
    return render_template("index.html")


@app.route("/visual/<name>")
def visual(name: str):
    if name is None:
        return index()
    name = name.strip()
    if len(name) == 0:
        return index()
    chart: Base = visualizations.get_chart(name)
    if chart is None:
        return index()
    return Markup(chart.render_embed())


if __name__ == "__main__":
    dbs.register_hook()
    app.run(host="0.0.0.0", port=8080, debug=True)
    print("start success.")
